/*
 * @Author: szx
 * @Date: 2022-02-11 15:24:44
 * @LastEditTime: 2022-02-11 15:54:18
 * @Description:
 * @FilePath: \leetcode\2000-2099\2006\2006.js
 */
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
// var countKDifference = function (nums, k) {
//     let res = 0;
//     const n = nums.length;
//     for (let i = 0; i < n; i++) {
//         for (let j = i + 1; j < n; j++) {
//             if (Math.abs(nums[j] - nums[i]) == k) res++;
//         }
//     }
//     return res;
// };

var countKDifference = function (nums, k) {
    const cnt = new Map();

    let res = 0;
    const n = nums.length;
    for (let i = 0; i < n; i++) {
        cnt.set(nums[i], (cnt.get(nums[i]) || 0) + 1);
        res += (cnt.get(nums[i] - k) || 0) + (cnt.get(nums[i] + k) || 0);
    }

    return res;
};
console.log(countKDifference([1, 2, 2, 1], 1));
